package org.budo.dubbo.protocol.http.dispatcher.websocket;

import java.util.Map;

import org.budo.dubbo.protocol.http.invocation.adapter.ProtocolRequest;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @author li
 */
public class WebSocketProtocolRequest implements ProtocolRequest {
    private String message;

    private JSONObject messageJson;

    /**
     * TODO 应该用反序列化方法构造这个实例
     */
    public WebSocketProtocolRequest(String message) {
        this.message = message;

        this.messageJson = JSON.parseObject(this.message);
    }

    public String getRequestId() {
        return this.messageJson.getString("requestId");
    }

    public String getInterfaceName() {
        return this.messageJson.getString("interfaceName");
    }

    public String getMethodName() {
        return this.messageJson.getString("methodName");
    }

    public Map<String, Object> getArguments() {
        JSONArray jsonArray = this.messageJson.getJSONArray("args");
        if (null == jsonArray || jsonArray.isEmpty()) {
            return null;
        }

        return jsonArray.getJSONObject(0);
    }

    @Override
    public String getHeader(String name) {
        JSONObject headers = this.messageJson.getJSONObject("headers");
        return null == headers ? null : headers.getString(name);
    }

    @Override
    public String toString() {
        return super.toString() + ", message=" + this.message + ", messageJson=" + this.messageJson;
    }

    @Override
    public String getRemoteAddr() {
        throw new RuntimeException();
    }

    @Override
    public Integer getRemotePort() {
        throw new RuntimeException();
    }
}